﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;

public class ParseUtility
{
    public string fileName = "/Resources/Txt/Language.bytes";
    Dictionary<int, string> keyValues = new Dictionary<int, string>();

    private static ParseUtility mSingleton;
    public static ParseUtility GetSingleton()
    {
        return mSingleton ?? (mSingleton = new ParseUtility());
    }

    public ParseUtility() { Init(); }

    public void Init()
    {
        string path = Application.dataPath + fileName;
        if (!File.Exists(fileName))
        {
            Debug.Log(path); return;
        }

        FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(file, Encoding.UTF8);

        try
        {
            Debug.Log(file.Name + " == " + file.Length);
            while (file.Position < file.Length)
            {
                keyValues.Add(br.ReadInt32(), br.ReadString());
            }
        }
        catch (Exception e)
        {
            Debug.LogError(e);
        }
        finally
        {
            br.Close();
            file.Close();
        }
    }

    public string GetTextById(int id)
    {
        string strTemp = string.Empty;
        keyValues.TryGetValue(id, out strTemp);
        if (string.IsNullOrEmpty(strTemp))
        {
            strTemp = id.ToString();
        }
        return strTemp.Replace("\\n", "\n");
    }
}